
import QtQuick 1.0

MyPage {
    id: pageOpenChats

    height: mytheme.displayHeight
    width: mytheme.displayWidth

    color: "white"
    anchors.fill: parent
    radius: mytheme.radiusMainWin
    clip: true

    property string clickedItem

    Text {
        id: txtBanner
        color: "gray"
        font.pixelSize: 40
        text: "Nothing open yet"
        anchors.centerIn: parent
        visible: xmppClient.openChats.count() === 0 ? true : false
        smooth: true
    }

    Component.onCompleted: {
        /* блокировка ориентации */
        main.appOrientation = main.orPortrait
    }

    Connections {
        target: xmppClient
        onChatOpened: {
            //console.log("*** onChatOpened:" + bareJid + "; " + isMuc);
        }
        onChatClosed: {
            //console.log("*** onChatClosed: " + bareJid + "; " + isMuc);
            if( isMuc ) {
                muc.leaveChat();
            }
        }
    }

    Component {
        id: componentDelegate
        Item {
            id: delegateItem
            width: gridView.cellWidth
            height: gridView.cellHeight
            property alias pic: delegateImage.source
            property bool currentChat: false
            function animBack() {
                itemAnimBack.start()
            }

            SequentialAnimation {
                id:animClose
                ParallelAnimation {
                    NumberAnimation {
                        from: 1
                        to: 0
                        property: "scale"
                        duration: 250
                        target: delegateItem
                    }
                    NumberAnimation {
                        from: 1
                        to: 0.2
                        property: "opacity"
                        duration: 250
                        target: delegateItem
                    }
                }
                ScriptAction {
                    script: {
                        if( contactItemType == 1 ) {
                            muc.jidRoom = contactJid
                        }
                        xmppClient.closeChat( contactJid )
                    }
                }
            }

            states: [
                State {
                    name: "view"
                    PropertyChanges { target: imgClose; visible: false }
                    PropertyChanges { target: wrapper; scale: 1.0 }
                    PropertyChanges { target: imgClose; opacity: 0 }
                    PropertyChanges { target: pageOpenChats; stateChatClose: false }
                    PropertyChanges { target: curtain; opacity: 0 }
                },
                State {
                    name: "close"
                    PropertyChanges { target: imgClose; visible: true }
                    PropertyChanges { target: wrapper; scale: 0.95 }
                    PropertyChanges { target: imgClose; opacity: 1.0 }
                    PropertyChanges { target: pageOpenChats; stateChatClose: true }
                    PropertyChanges { target: curtain; opacity: 0.5 }
                }
            ]
            state: "view"
            transitions: Transition {
                NumberAnimation { properties: "scale, opacity"; duration: 300 }
            }

            Rectangle {
                id: wrapper
                border.color: "gray"
                border.width: currentChat ? 2 : 1
                color: "lightgray"
                radius: 5
                width: gridView.cellWidth - 10
                height: gridView.cellHeight - 10
                anchors.centerIn: parent
                //clip: true

                Rectangle {
                    id: curtain
                    z: 4
                    anchors.fill: parent
                    color: "black"
                    radius: wrapper.radius
                }

                Image {
                    id: imgClose
                    z: 5
                    source: "qrc:/qml/images/app_close.png"
                    anchors.right: parent.right
                    anchors.rightMargin: -10
                    anchors.top: parent.top
                    anchors.topMargin: - 10
                    opacity: 1.0
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            animClose.running = true
                        }
                    }
                }

                Image {
                    id: imgPresence
                    source: contactPicStatus //TODO: in case MUC change it to my status
                    anchors.top: parent.top; anchors.topMargin: 5
                    anchors.left: parent.left; anchors.leftMargin: 5
                    z: 2

                    Text {
                        id: txtUnreadMsg
                        text: contactUnreadMsg
                        font.pixelSize: 22
                        anchors.centerIn: parent
                        visible: contactUnreadMsg != 0
                        z: 1
                    }

                    Image {
                        id: imgNewMsg
                        source: "qrc:/qml/images/message.png"
                        anchors.centerIn: parent
                        smooth: true
                        scale: 0.8
                        visible: contactUnreadMsg != 0
                        SequentialAnimation {
                            running: contactUnreadMsg != 0
                            loops: Animation.Infinite
                            NumberAnimation {
                                target: imgNewMsg
                                property: "opacity"
                                from: 1; to: 0.4
                                duration: 1300
                                easing.type: Easing.InOutQuad
                            }
                            NumberAnimation {
                                target: imgNewMsg
                                property: "opacity"
                                from: 0.4; to: 1
                                duration: 1300
                                easing.type: Easing.InOutQuad
                            }
                        }
                    }
                }

                Image {
                    id: imgFrame
                    anchors.centerIn: parent
                    smooth: true
                    source: "qrc:/qml/images/chat_frame.png"
                    z:1
                }
                Image {
                    id: delegateImage
                    z: 0
                    source: contactItemType == 0 ? (contactPicAvatar === "" ? "qrc:/qml/images/avatar.png" : contactPicAvatar) : "qrc:/qml/images/muc.png"
                    anchors.centerIn: parent
                    smooth: true
                    width: 120
                    height: 120
                    Rectangle {
                        z: -1
                        color: "white"
                        height: 160
                        width: 160
                        radius: 80
                        anchors.centerIn: parent
                    }
                }


                Text {
                    id: txtNameOrJid
                    z: 1
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.bottom: parent.bottom
                    anchors.bottomMargin: contactName === "" ? 20 : 30
                    text: contactName === "" ? contactJid : contactName
                    font.pixelSize: 20
                    color: "blue"
                    Component.onCompleted: {
                        if( delegateItem.width < txtNameOrJid.width ) {
                            var nName = txtNameOrJid.text;
                            var pos = nName.indexOf("@");
                            if( pos > 1 )
                            {
                                var xName = nName.substring(0, pos+1);
                                xName += "\n";
                                xName += nName.substring(pos+1);
                                txtNameOrJid.text = xName;
                                txtNameOrJid.anchors.bottomMargin = 16
                                txtNameOrJid.font.pixelSize = 18
                                if( delegateItem.width < txtNameOrJid.width ) {
                                    txtNameOrJid.font.pixelSize = 16
                                    txtNameOrJid.wrapMode = TextEdit.WrapAtWordBoundaryOrAnywhere
                                }
                            }
                            else
                            {
                                txtNameOrJid.font.pixelSize = 16
                                txtNameOrJid.wrapMode = TextEdit.WrapAtWordBoundaryOrAnywhere
                            }
                        }
                    }
                }
                Text {
                    z: 1
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.bottom: parent.bottom
                    anchors.bottomMargin: 7
                    text: contactJid
                    visible: contactName === "" ? false : true
                    font.pixelSize: 16
                    color: "gray"
                    font.italic: true
                }

                transform: [
                    Rotation {
                        id: plateRotation
                        angle: -90
                        axis { x: 0; y: 1; z: 0 }
                        origin.x: -250 //-200
                        origin.y: -10  //50
                    },
                    Rotation {
                        id: plateFlip
                        angle: 0
                        axis { x: 1; y: 0; z: 0 }
                        origin.x: 50
                        origin.y: 50
                    }
                ]

                /* itemAnim - вперед: вход на страницу */
                SequentialAnimation {
                    id: itemAnim
                    PauseAnimation { duration: Math.random()*600 }
                    ParallelAnimation {
                        NumberAnimation {
                            target: plateRotation
                            properties: "angle"
                            easing.type: Easing.InOutCubic //Easing.OutCubic
                            from: -90
                            to: 0
                            duration: 800
                        }
                        NumberAnimation {
                            target: delegateItem
                            properties: "opacity"
                            easing.type: Easing.InOutCubic
                            from: 0.3
                            to: 1
                            duration: 800
                        }
                    }
                }

                /* itemAnimBack - назад: уход со страницы */
                ParallelAnimation {
                    id: itemAnimBack
                    property int __timeAnim: 700 //длительность всей анимации
                    SequentialAnimation {
                        PauseAnimation {
                            duration:  delegateItem.currentChat ? (gridView.count == 1 ? 100 : itemAnimBack.__timeAnim) : Math.random()*itemAnimBack.__timeAnim
                        }
                        ParallelAnimation {
                            NumberAnimation {
                                target: plateRotation
                                properties: "angle"
                                easing.type: Easing.OutCubic
                                from: 0
                                to: -90
                                duration: 500
                            }
                            NumberAnimation {
                                target: delegateItem
                                properties: "opacity"
                                easing.type: Easing.InOutCubic
                                from: 1
                                to: 0.3
                                duration: 500
                            }
                        }
                    }
                    SequentialAnimation {
                        id: shakeAnim
                        //PauseAnimation { duration: Math.random()*50 }
                        NumberAnimation { target: delegateItem; property: "rotation"; to:  2; duration: 50 }
                        NumberAnimation { target: delegateItem; property: "rotation"; to: -2; duration: 100 }
                        NumberAnimation { target: delegateItem; property: "rotation"; to:  0; duration: 50 }
                        loops: delegateItem.currentChat ? 7 : 0
                        alwaysRunToEnd: true
                    }
                    ScriptAction {
                        script: {
                            if( delegateItem.currentChat  ) {
                                xmppClient.chatJid = contactJid
                                __pageNextPause = gridView.count == 1 ? 400 : itemAnimBack.__timeAnim + 300
                                if( contactItemType == 0 ) {
                                    __pageNext = "qrc:/qml/MessagesPage.qml"
                                } else {
                                    __pageNext = "qrc:/qml/MucPage.qml"
                                }
                                xmppClient.resetUnreadMessages( contactJid ) //сброс непрочитанных сообщ.
                                animClosePage.running = true //запуск анимации закрытия окна
                            }
                        }
                    }
                } //ParallelAnimation

                MouseArea {
                    id: delegateMouseArea
                    hoverEnabled: true
                    anchors.fill: parent
                }

                Component.onCompleted: {
                    itemAnim.start()
                }

            }
        } //Item

    } //Component { componentDelegate }

    Rectangle {
        id: panelHeader
        z: 1
        width: parent.width
        height: 15
        anchors.top: parent.top
        anchors.left: parent.left
        gradient: Gradient {
            GradientStop { position: 0; color: pageOpenChats.color }
            GradientStop { position: 0.5; color: pageOpenChats.color }
            GradientStop { position: 1; color: "transparent" }
        }
    }

    Rectangle {
        id: panelFooter
        z: 1
        width: parent.width
        height: 15
        anchors.bottom: toolBar.top
        anchors.left: parent.left
        gradient: Gradient {
            GradientStop { position: 0; color: "transparent" }
            GradientStop { position: 0.5; color: pageOpenChats.color }
            GradientStop { position: 1; color: pageOpenChats.color }
        }
    }

    property bool stateChatClose: false
    GridView {
        id: gridView
        model: xmppClient.openChats
        anchors.top: panelHeader.bottom
        anchors.bottom: panelFooter.top
        width: parent.width
        height: parent.height
        cellHeight: 240
        cellWidth: 240
        delegate: componentDelegate
        focus: true
        MouseArea {
            id: ma
            enabled: !stateChatClose
            anchors.fill: parent
            onPressAndHold: {
                for( var L=0; L<gridView.count; L++ ) {
                    gridView.currentIndex = L
                    if( gridView.currentItem.state == "view" ) {
                        gridView.currentItem.state = "close"
                    } else {
                        gridView.currentItem.state = "view"
                    }
                }
            }
            onClicked: {
                var currItem = gridView.indexAt( ma.mouseX , ma.mouseY )
                if( currItem >= 0 )
                {
                    for( var L=0; L<gridView.count; L++ ) {
                        if( L !== currItem ) {
                            gridView.currentIndex = L
                            gridView.currentItem.currentChat = false
                            gridView.currentItem.animBack()
                        } else {
                            gridView.currentIndex = L
                            panelHeader.visible = false
                            panelFooter.visible = false

                            gridView.currentItem.border

                            gridView.currentItem.currentChat = true
                            gridView.currentItem.animBack()
                        }
                    }
                }

            } //onClicked
        } //MouseArea
    } //GridView



    /*****************************************************************************/
    property string __pageNext: "qrc:/qml/RosterPage.qml"
    property int __pageNextPause: 1000

    SequentialAnimation {
        id: animClosePage
        running: false
        PauseAnimation { duration: __pageNextPause }
        ScriptAction {
            script: {
                //main.loadPage = __pageNext
                pageOpenChats.closePage( __pageNext )
            }
        }
    }

    ToolBar {
        id: toolBar
        z: 5
        ToolButton {
            id: toolBarButtonDialog
            icon: "qrc:/qml/images/bar_roster.png"
            anchors.left: parent.left
            anchors.leftMargin: 30
            onClicked: {
                for( var L=0; L<gridView.count; L++ ) {
                    gridView.currentIndex = L
                    gridView.currentItem.animBack()
                }
                if( xmppClient.openChats.count() === 0 ) {
                    __pageNextPause = 100
                } else {
                    __pageNextPause = 1200 //1600
                }
                __pageNext = "qrc:/qml/RosterPage.qml"
                animClosePage.running = true
            }
            visible: !stateChatClose
            pauseAnim: 500
        }

        ToolButton {
            id: toolBarButtonNormalState
            icon: "qrc:/qml/images/bar_ok.png"
            //anchors.left: parent.left
            //anchors.leftMargin: 100
            anchors.horizontalCenter: parent.horizontalCenter
            onClicked: {
                for( var L=0; L<gridView.count; L++ ) {
                    gridView.currentIndex = L
                    gridView.currentItem.state = "view"
                }
                stateChatClose = false
            }
            visible: stateChatClose
        }

        /*ToolButton {
            id: toolBarButtonCloseAll
            icon: "qrc:/qml/images/bar_close.png"
            anchors.right: parent.right
            anchors.rightMargin: 100
            onClicked: {
                for( var L=0; L<gridView.count; L++ ) {
                    gridView.currentIndex = L
                    gridView.currentItem.state = "view"
                    //cppMyXmppClient.closeChat( contactJid )
                }
                stateChatClose = false
            }
            visible: stateChatClose
        }*/
    }


}
